package com.wnzt.baszh.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.URLDecoder;
import java.net.UnknownHostException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.itextpdf.text.DocumentException;
import com.wnzt.baszh.entity.SzhCxmbtjmx;
import com.wnzt.baszh.entity.Tsysuser;
import com.wnzt.baszh.service.IMedicalCheckService;
import com.wnzt.baszh.service.IMedicalShootService;
import com.wnzt.baszh.util.common.BaseController;
import com.wnzt.baszh.util.common.FTPUtil;
import com.wnzt.baszh.util.common.FileEncodeAndDecode;
import com.wnzt.baszh.util.common.FileUtil;
import com.wnzt.baszh.util.common.Ftp;
import com.wnzt.baszh.util.common.GlobalStatic;
import com.wnzt.baszh.util.common.PageHelper;
import com.wnzt.baszh.util.common.PrintUtils;
import com.wnzt.baszh.util.common.SetSystemProperty;

/**
 * 病案查询管理控制器
 * auth hlq
 */

@Controller
@RequestMapping("/MedicalCheckManage")
public class MedicalCheckController extends BaseController{
    
    @Autowired
    private IMedicalCheckService iMedicalCheckService;
    
    @Autowired
    private IMedicalShootService medicalShootService;
    /**
     *跳转病案查询页面
     */
    @RequestMapping("/MedicalRecordInquiry")
    public String MedicalRecordInquiry(){
        return "MedicalCheckManage/MedicalRecordInquiry";
    }
    
    /**
     *跳转病案浏览审批页面
     */
    @RequestMapping("/MedicalBrowseExamination")
    public String MedicalBrowseExamination(){
        return "MedicalCheckManage/MedicalBrowseExamination";
    }
    
    /**
     *跳转病案浏览批量审批页面
     */
    @RequestMapping("/MedicalBatchExamination")
    public String MedicalBatchExamination(){
        return "MedicalCheckManage/MedicalBatchExamination";
    }
    
    /**
     *跳转病案图片浏览页面
     */
    @RequestMapping("/MedicolRecordPictureView")
    public String MedicolRecordPictureView(){
        return "MedicalCheckManage/MedicolRecordPictureView";
    }
    
    
    /**
     *跳转到【病案错误报告处理 】 页
     */
    @RequestMapping("/MedicolErrorsb")
    public String MedicolErrorsb(){
        return "MedicalCheckManage/MedicolErrorsb";
    } 
    
    /**
     *跳转到【病案-人员浏览统计 】 页
     */
  	@RequestMapping("/MedicalBrowseStatistical")
  	public String MedicalBrowseStatistical(){
  		return "MedicalCheckManage/MedicalBrowseStatistical";
  	}
  	
    /**
     * 根据医生类型字段加载所有该类型下的医生
     */
    @RequestMapping("loadDoctorByDocType")
    @ResponseBody
    public Object loadDoctorByDocType(HttpServletRequest request){
        String code = request.getParameter("code");  //获取医生类型编号
        return iMedicalCheckService.loadDoctorByDocType(code);
    }
    
    /**
     * 添加模板，添加模板条件
     */
    @RequestMapping("addConditionTemp")
    @ResponseBody
    public Object addConditionTemp(HttpServletRequest request){
        Tsysuser userObject = (Tsysuser) request.getSession().getAttribute(GlobalStatic.USER_SESSION_OBJECT);
        String TempMC = request.getParameter("TempMC");  //模板名称
        Map<String, Object> map = new HashMap<String, Object>();
        
        map = returnRequstMap(request);
        map.put("TempMC", TempMC);
        map.put("fcode", userObject.getFcode());
        
        return iMedicalCheckService.addConditionTemp(map);
    }
    
    /**
     * 修改模板条件
     */
    @RequestMapping("editConditionTemp")
    @ResponseBody
    public Object editConditionTemp(HttpServletRequest request){
        Tsysuser userObject = (Tsysuser) request.getSession().getAttribute(GlobalStatic.USER_SESSION_OBJECT);
        String TempID = request.getParameter("TempID");            //模板id
        Map<String, Object> map = new HashMap<String, Object>();
        
        map = returnRequstMap(request);
        map.put("TempID", TempID);
        map.put("fcode", userObject.getFcode());
        return iMedicalCheckService.editConditionTemp(map);
    }
    
    /**
     * 静态方法  用于接受参数  返回map
     */
    public Map<String, Object> returnRequstMap(HttpServletRequest request) {
        Map<String, Object> map  = new HashMap<String, Object>();
        
        String checkCydetkh = request.getParameter("checkCydetkh");  //出院科室科号拼接字符串(带引号)
        String checkDocbh = request.getParameter("checkDocbh");      //医生或护士工号拼接字符串(带引号)
        
        String FRQLX = request.getParameter("FRQLX");                //日期类型(出院日期、入院日期)
        String FQSRQ = request.getParameter("FQSRQ");                //起始日期()
        String FJSRQ = request.getParameter("FJSRQ");                //结束日期()
        String FSEXLX = request.getParameter("FSEXLX");              //性别类型(0、全部  1、男 2、女)
        
        String FQSAGE = request.getParameter("FQSAGE");              //起始年龄值()
        String FJSAGE = request.getParameter("FJSAGE");              //结束年龄值()
        String FAGELX = request.getParameter("FAGELX");              //年龄类型(1、年 2、月)
        
        String FPRNTEXT = request.getParameter("FPRNTEXT");          //病案号值,同时将中文逗号转英文逗号
        String FNAMETEXT = request.getParameter("FNAMETEXT");        //姓名值
        String FZDBMMCVAL = request.getParameter("FZDBMMCVAL");      //诊断编码或名称值
        String FSSBMMCVAL = request.getParameter("FSSBMMCVAL");      //手术编码或名称值
        if (!"".equals(FPRNTEXT)) {
            FPRNTEXT = FPRNTEXT.replaceAll("，", ",");
        }
        if (!"".equals(FNAMETEXT)) {
            FNAMETEXT = FNAMETEXT.replaceAll("，", ",");
        }
        
        String FDOCLX = request.getParameter("FDOCLX");              //医生类型值
        
        String FZDBMMC = request.getParameter("FZDBMMC");            //诊断编码或名称(FICDM、诊断编码  FJBNAME、诊断名称)
        if (!"".equals(FZDBMMCVAL)) {
            FZDBMMCVAL = FZDBMMCVAL.replaceAll("，", ",");
        }
        
        String FZDLX = request.getParameter("FZDLX");                //诊断类型
        
        String FSSBMMC = request.getParameter("FSSBMMC");            //手术编码或名称(FOPCODE、手术编码  FOP、手术名称)
        if (!"".equals(FSSBMMCVAL)) {
            FSSBMMCVAL = FSSBMMCVAL.replaceAll("，", ",");
        }
        
        String FSSLX = request.getParameter("FSSLX");                //手术类型(3、全部 0、主要手术 1、其他手术)
        
        map.put("checkCydetkh", checkCydetkh);
        map.put("checkDocbh", checkDocbh);
        
        map.put("FRQLX", FRQLX);
        map.put("FQSRQ", FQSRQ);
        map.put("FJSRQ", FJSRQ);
        map.put("FSEXLX", FSEXLX);
        
        map.put("FQSAGE", FQSAGE);
        map.put("FJSAGE", FJSAGE);
        map.put("FAGELX", FAGELX);
        
        map.put("FPRNTEXT", FPRNTEXT);
        map.put("FNAMETEXT", FNAMETEXT);
        map.put("FDOCLX", FDOCLX);
        
        map.put("FZDBMMC", FZDBMMC);
        map.put("FZDBMMCVAL", FZDBMMCVAL);
        map.put("FZDLX", FZDLX);
        
        map.put("FSSBMMC", FSSBMMC);
        map.put("FSSBMMCVAL", FSSBMMCVAL);
        map.put("FSSLX", FSSLX);
        
        return map;
    }
    
    /**
     * 根据条件查询模板id修改模板的名称
     */
    @RequestMapping("editConditionTempName")
    @ResponseBody
    public Object editConditionTempName(HttpServletRequest request){
        String name = request.getParameter("name");  //模板名称
        String mbID = request.getParameter("mbID");  //模板id
        return iMedicalCheckService.editConditionTempName(name, mbID);
    }
    
    /**
     * 根据条件查询模板id删除该模板信息
     */
    @RequestMapping("deleteConditionTemp")
    @ResponseBody
    public Object deleteConditionTemp(HttpServletRequest request){
        String mbID = request.getParameter("mbID");  //模板id
        return iMedicalCheckService.deleteConditionTemp(mbID);
    }
    
    /**
     * 公用代码--加载个人病案查询模板
     * @author hlq
     * @param request
     * @param ftype 模板类型 ： 1 病案查询    2 病案高级查询
     * @return
     * @update [lv tang wei]
     * [2017年6月6日]
     */
    @RequestMapping("loadConditionTemple")
    @ResponseBody
    public Object loadConditionTemple(HttpServletRequest request,String ftype){
        Tsysuser userObject = (Tsysuser) request.getSession().getAttribute(GlobalStatic.USER_SESSION_OBJECT);
        return iMedicalCheckService.loadConditionTemple(userObject.getFcode(),ftype);
    }
    
    /**
     * 根据条件查询模板id加载条件明细值
     */
    @RequestMapping("loadConditionByTemple")
    @ResponseBody
    public Object loadConditionByTemple(HttpServletRequest request){
        String mbID = request.getParameter("mbID");  //模板id
        return iMedicalCheckService.loadConditionByTemple(mbID);
    }
    
    /**
     * 根据字段模板id加载字段信息
     */
    @RequestMapping("loadFieldsByTempId")
    @ResponseBody
    public Object loadFieldsByTempId(HttpServletRequest request){
        String mbID = request.getParameter("mbID");  //模板id
        return iMedicalCheckService.loadFieldsByTempId(mbID);
    }
    
    /**
     * 病案查询页面点击查询执行事件,返回拼接sql语句后查询出的数据
     */
    @RequestMapping("SubmitConditionCheck")
    @ResponseBody
    public Object SubmitConditionCheck(HttpServletRequest request){
        
        Tsysuser userObject = (Tsysuser) request.getSession().getAttribute(GlobalStatic.USER_SESSION_OBJECT);
        Map<String, Object> map = new HashMap<String, Object>();
        
        map = returnRequstMap(request);
        map.put("fcode", userObject.getFcode());
        map.put("fname", userObject.getFname());
        List<Map<String, Object>> list=null;
		try {
			list = iMedicalCheckService.SubmitConditionCheck(map);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
        
        Object jsonArray = JSON.toJSONStringWithDateFormat(list, "yyyy-MM-dd", SerializerFeature.WriteDateUseDateFormat);
        return jsonArray;
        
    }
    
    /**
     * 病案查询页面单个病案申请
     */
    @RequestMapping("confirmSApply")
    @ResponseBody
    public Object confirmSApply(HttpServletRequest request){
        Tsysuser userObject = (Tsysuser) request.getSession().getAttribute(GlobalStatic.USER_SESSION_OBJECT);
        
        String fzyid = request.getParameter("fzyid");  //住院id
        String sApplyPurpose = request.getParameter("sApplyPurpose");  //申请目的
        String sBrowseDays = request.getParameter("sBrowseDays");  //申请浏览天数
        String sApplyRemark = request.getParameter("sApplyRemark");  //申请描述
        
        Map<String, Object> map = new HashMap<String, Object>();
        
        map.put("fzyid", fzyid);
        map.put("sApplyPurpose", sApplyPurpose);
        map.put("sBrowseDays", sBrowseDays);
        map.put("sApplyRemark", sApplyRemark);
        map.put("fcode", userObject.getFcode());
        map.put("fjysqr", userObject.getFname());
        
        return iMedicalCheckService.confirmSApply(map);
    }
    
    /**
     * 病案查询页面批量申请确认
     */
    @RequestMapping("confirmBApply")
    @ResponseBody
    public Object confirmBApply(HttpServletRequest request){
        Tsysuser userObject = (Tsysuser) request.getSession().getAttribute(GlobalStatic.USER_SESSION_OBJECT);
        
        String fsqtjwz = request.getParameter("fsqtjwz"); 
        String fsqtjsql = request.getParameter("fsqtjsql"); 
        String ftype = request.getParameter("ftype"); 
        String bApplyPurpose = request.getParameter("bApplyPurpose");  //申请目的
        String bBrowseDays = request.getParameter("bBrowseDays");  //申请浏览天数
        String bApplyRemark = request.getParameter("ApplyRemark");  //申请描述
        
        Map<String, Object> map = new HashMap<String, Object>();
        if(ftype==null || "1".equals(ftype)){
        	map = returnRequstMap(request);
        }
        
        map.put("fsqtjwz", fsqtjwz);
        map.put("fsqtjsql", fsqtjsql);
        map.put("ftype", ftype);
        map.put("bApplyPurpose", bApplyPurpose);
        map.put("bBrowseDays", bBrowseDays);
        map.put("bApplyRemark", bApplyRemark);
        map.put("fcode", userObject.getFcode());
        map.put("fjysqr", userObject.getFname());
        
        return iMedicalCheckService.confirmBApply(map);
    }
    
    /**
     * 病案浏览审批页面查询数据
     */
    @RequestMapping("checkPurposeDataByUser")
    @ResponseBody
    public PageHelper checkPurposeDataByUser(HttpServletRequest request){
        Tsysuser userObject = (Tsysuser) request.getSession().getAttribute(GlobalStatic.USER_SESSION_OBJECT);
        
        String dateType = request.getParameter("dateType");         //日期类型(1 申请日期  2出院日期)
        String startDate = request.getParameter("startDate");       //起始日期时间
        String endDate = request.getParameter("endDate");           //结束日期时间
        String fjymd = request.getParameter("fjymd");               //借阅目的id
        
        String fspzt = request.getParameter("fspzt");               //审批状态(1:全部,2:中间流程,3:批准,4:驳回)
        String isApproval = request.getParameter("isApproval");     //是否已经审批(true 需要审批的  false 包括需要审批和已经审批过的)
        String scheckNum = request.getParameter("scheckNum");       //病案号、条码号或住院号id
        String scheckFname = request.getParameter("scheckFname");   //患者姓名
        String scheckFsqr = request.getParameter("scheckFsqr");     //申请人
        
        String page = request.getParameter("page");
        String rows = request.getParameter("rows");
        
        Map<String, Object> map = new HashMap<String, Object>();
        
        
        map.put("dateType", dateType);
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("fjymd", fjymd);
        map.put("fspzt", fspzt);
        map.put("isApproval", isApproval);
        
        map.put("user", userObject);
        map.put("scheckNum", scheckNum);
        map.put("scheckFname", scheckFname);
        map.put("scheckFsqr", scheckFsqr);
        map.put("page", page);
        map.put("rows", rows);
        
        return iMedicalCheckService.checkPurposeDataByUser(map);
    }
    
    /**
     * 根据借阅目的id和审批级别 判断下级审批级别是否存在审批人员
     */
    @RequestMapping("checkNextExaminationPerson")
    @ResponseBody
    public Object checkNextExaminationPerson(HttpServletRequest request){
        String fjymdid = request.getParameter("fjymdid");  //借阅目的id
        String fdqspjb = request.getParameter("fdqspjb");  //当前流程
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("fjymdid", fjymdid);
        map.put("fdqspjb", fdqspjb);
        return iMedicalCheckService.checkNextExaminationPerson(map);
    }
    
    /**
     * 病案浏览审批审批通过方法
     */
    @RequestMapping("submitsApprovalMedicol")
    @ResponseBody
    public Object submitsApprovalMedicol(HttpServletRequest request){
        Tsysuser userObject = (Tsysuser) request.getSession().getAttribute(GlobalStatic.USER_SESSION_OBJECT);
        
        String fsqid = request.getParameter("fsqid");  //申请id
        String fqsrq = request.getParameter("fqsrq");  //起始日期时间戳
        
        //时间戳转日期格式
        SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(fqsrq);
        Date date = new Date(lt);
        fqsrq = sFormat.format(date);
        
        String fspms = request.getParameter("fspms");  //审批描述
        String fspday = request.getParameter("fspday");  //浏览数值
        String fspdayunit = request.getParameter("fspdayunit");  //浏览数值单位（1、天  2、小时）
        
        String fspzt = request.getParameter("fspzt");  //审批状态
        String fdqlc = request.getParameter("fdqlc");  //当前流程
        String fxjlc = request.getParameter("fxjlc");  //下级流程
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("fsqid", fsqid);
        map.put("fqsrq", fqsrq);
        map.put("fspms", fspms);
        map.put("fspday", fspday);
        map.put("user", userObject);
        map.put("fspdayunit", fspdayunit);
        map.put("fspzt", fspzt);
        map.put("fdqlc", fdqlc);
        map.put("fxjlc", fxjlc);
        return iMedicalCheckService.submitsApprovalMedicol(map);
    }
    
    /**
     * 病案浏览审批审批不通过方法
     */
    @RequestMapping("submitsNotApprovalMedicol")
    @ResponseBody
    public Object submitsNotApprovalMedicol(HttpServletRequest request){
        Tsysuser userObject = (Tsysuser) request.getSession().getAttribute(GlobalStatic.USER_SESSION_OBJECT);
        String fjlid = request.getParameter("fjlid");  //审批记录id
        String fxjlc = request.getParameter("fxjlc");  //审批下级流程
        String fspms = request.getParameter("fspms");  //审批描述
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("fjlid", fjlid);
        map.put("fxjlc", fxjlc);
        map.put("user", userObject);
        map.put("fspms", fspms);
        return iMedicalCheckService.submitsNotApprovalMedicol(map);
    }
    
    /**
     * 病案批量浏览审批查询
     */
    @RequestMapping("checkPurposeDataBatch")
    @ResponseBody
    public PageHelper checkPurposeDataBatch(HttpServletRequest request){
        Tsysuser userObject = (Tsysuser) request.getSession().getAttribute(GlobalStatic.USER_SESSION_OBJECT);
        
        String startDate = request.getParameter("startDate");  //申请起始日期
        String endDate = request.getParameter("endDate");      //申请结束日期
        String fjymd = request.getParameter("fjymd");          //借阅目的id
        String scheckFsqr = request.getParameter("scheckFsqr");//申请人
        
        String page = request.getParameter("page");
        String rows = request.getParameter("rows");
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("startDate", startDate);
        map.put("endDate", endDate);
        map.put("fjymd", fjymd);
        map.put("scheckFsqr", scheckFsqr);
        map.put("user", userObject);
        
        map.put("page", page);
        map.put("rows", rows);
        return iMedicalCheckService.checkPurposeDataBatch(map);
    }
    
    /**
     * 病案批量浏览审批审批通过方法
     */
    @RequestMapping("submitbApprovalMedicol")
    @ResponseBody
    public Object submitbApprovalMedicol(HttpServletRequest request){
        Tsysuser userObject = (Tsysuser) request.getSession().getAttribute(GlobalStatic.USER_SESSION_OBJECT);
        
        String fsqid = request.getParameter("fsqid");  //申请id
        String fqsrq = request.getParameter("fqsrq");  //起始日期时间戳
        
        //时间戳转日期格式
        SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(fqsrq);
        Date date = new Date(lt);
        fqsrq = sFormat.format(date);
        
        String fspms = request.getParameter("fspms");  //审批描述
        String fspday = request.getParameter("fspday");  //浏览数值
        String fspdayunit = request.getParameter("fspdayunit");  //浏览数值单位（1、天  2、小时）
        
        String fspzt = request.getParameter("fspzt");  //审批状态
        String fdqlc = request.getParameter("fdqlc");  //当前流程
        String fxjlc = request.getParameter("fxjlc");  //下级流程
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("fsqid", fsqid);
        map.put("fqsrq", fqsrq);
        map.put("fspms", fspms);
        map.put("fspday", fspday);
        map.put("user", userObject);
        map.put("fspdayunit", fspdayunit);
        map.put("fspzt", fspzt);
        map.put("fdqlc", fdqlc);
        map.put("fxjlc", fxjlc);
        return iMedicalCheckService.submitbApprovalMedicol(map);
    }
    
    /**
     * 病案批量浏览审批审批不通过方法
     */
    @RequestMapping("submitbNotApprovalMedicol")
    @ResponseBody
    public Object submitbNotApprovalMedicol(HttpServletRequest request){
        Tsysuser userObject = (Tsysuser) request.getSession().getAttribute(GlobalStatic.USER_SESSION_OBJECT);
        String fjlid = request.getParameter("fjlid");  //审批记录id
        String fxjlc = request.getParameter("fxjlc");  //审批下级流程
        String fspms = request.getParameter("fspms");  //审批描述
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("fjlid", fjlid);
        map.put("fxjlc", fxjlc);
        map.put("user", userObject);
        map.put("fspms", fspms);
        return iMedicalCheckService.submitbNotApprovalMedicol(map);
    }
    
    /**
     * 根据借阅目的id和下级审批级别判断当前用户是否具有相应的审批权限
     */
    @RequestMapping("checkUserHaveJuris")
    @ResponseBody
    public Object checkUserHaveJuris(HttpServletRequest request){
        Tsysuser userObject = (Tsysuser) request.getSession().getAttribute(GlobalStatic.USER_SESSION_OBJECT);
        String fjymdid = request.getParameter("fjymdid");  //借阅目的id
        String fdqspjb = request.getParameter("fdqspjb");  //当前流程
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("fjymdid", fjymdid);
        map.put("fdqspjb", fdqspjb);
        map.put("fcode", userObject.getFcode());
        return iMedicalCheckService.checkUserHaveJuris(map);
    }
    
    /**
     * 病案浏览获取图片树
     * @param request
     * @return
     */
    @RequestMapping("/getTree")
    @ResponseBody
    public Object getTree(HttpServletRequest request) {
        
        //获取当前用户
        Tsysuser user = (Tsysuser) request.getSession().getAttribute(GlobalStatic.USER_SESSION_OBJECT);
        String name = user.getFname();//用户名
        String fcode = user.getFcode();   //当前用户编号
        String fzyid = request.getParameter("fzyid");
        String id = request.getParameter("id");  //申请id
        String fprn = request.getParameter("fprn");//病案号
        String ftimes=request.getParameter("ftimes");//住院次数
        String DATE = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        String ip = "";   //获取当前本机IP
        
        try {
            ip = InetAddress.getLocalHost().toString();
        } catch (UnknownHostException e) {
            e.printStackTrace();
        } 
        
        UUID uuid = UUID.randomUUID(); //获取当前本机uuid
        
        Map<String, Object> paramMap = new HashMap<String,Object>();
        paramMap.put("fzyid", fzyid);
        paramMap.put("ip", ip);
        paramMap.put("uuid", uuid.toString());
        paramMap.put("fcode", fcode);
        paramMap.put("fprn", fprn);
        paramMap.put("name", name);
        paramMap.put("DATE", DATE);
        
        Map<String, Object> maps = new HashMap<String,Object>();
        maps.put("fzyid", fzyid);
        maps.put("user", user);
        maps.put("id", id);
        maps.put("date", date);
        List<Map<String, Object>> results = new ArrayList<Map<String,Object>>();   
        try {
			
	        List<Map<String, Object>> thirdList = medicalShootService.getTree(paramMap); // 根据病案的住院流水号查询病案信息图片
	        List<Map<String, Object>> listOptions = iMedicalCheckService.getListOptions(maps); // 根据用户判断图片分类模板权限
	        List<Map<String, Object>> secondList = new ArrayList<Map<String,Object>>();
	        //第一层菜单名
	        Map<String, Object> map = new HashMap<String,Object>();
	        map.put("id", "01");
	        map.put("text", "病案封面");
	        map.put("children", secondList);
	        results.add(map);
	        for (Map<String, Object> m : listOptions) {
	            Map<String, Object> map2 = new HashMap<String,Object>();
	            map2.put("id", String.valueOf(m.get("FID")));
	            map2.put("text", "<span title='未归档'>"+m.get("FNAME")+"&nbsp;<sup><font size='0.5em' color='red'>未</font></sup></span>");
	            map2.put("attributes", m.get("FCODE"));
	            map2.put("isJuris", m.get("isJuris")); //1 代表具有权限  2不具有权限，需要申请
	            
	            if (!thirdList.isEmpty()) {
	                List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
	                map2.put("children", list);
	                
	                for (Map<String, Object> m2 : thirdList) {
	                    
	                    if(String.valueOf(m2.get("FTPFL")).equals(m.get("FCODE"))) {
	                        
	                        String filetype = m2.get("ftype")+"";   // 文件类型  1: pdf 0: 图片
	                        if ("1".equals(filetype)) {
	                            map2.put("fileType", 1);
	                            map2.put("text", "<span title='已归档'>"+m.get("FNAME")+"&nbsp;<sup><font size='0.5em' color='green'>已</font></sup></span>");
	                            map2.put("path", m2.get("FSCDZ"));
	                            map2.put("filename", m.get("FNAME")+".pdf");
	                            
	                        } else if(m2.get("ftpym") != null) {
	                            Map<String,Object> map3 = new HashMap<String,Object>();
	                            map3.put("id", m2.get("FID") + "," + m2.get("FTPBH"));
	                            map3.put("text", "第" + m2.get("ftpym") + "页");
	                            map3.put("iconCls", "");
	                            map3.put("attributes", m2.get("fscdz"));
	                            map3.put("type", m2.get("ftype"));
	                            list.add(map3); 
	                        }
	                    }
	                }
	            }
	            secondList.add(map2);
	        }
        } catch (Exception e) {
			e.printStackTrace();
		}
        return results;
    }
    
    @RequestMapping(value = "getFile")
    @ResponseBody
	public Map<String,Object> getFile(HttpServletRequest request,
			HttpServletResponse response) {
    	Map<String,Object> reMap=new HashMap<String,Object>();
    	String type=request.getParameter("type");//0图片，1pdf
    	String encryptpath=request.getParameter("path");//encryptpath路径
    	String ftpdir=encryptpath.substring(0,encryptpath.lastIndexOf("/"));
    	String filename=encryptpath.substring(encryptpath.lastIndexOf("/")+1);
    	String postfix=type.equals("0")?".jpg":".pdf";
    	/**
    	 * 第一步，将pdf文件从ftp服务器下载。
    	 * 第二步，将pdf文件解密。
    	 * 第三步，将pdf文件流解析成字节流。
    	 */
    	/*取资源文档目录*/
		String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
		/*读取配置文件*/
		Map<String,String> prop=SetSystemProperty.propertiesToMap(path+"/config.properties");
		/*取项目根目录*/
		String strDirPath = request.getSession().getServletContext().getRealPath("/");
		/*本地保存目录*/
		String localPath=strDirPath+prop.get("pdf.temp.path");
		/*创建多级本地目录*/
		FileUtil.createMultilayerFile(localPath);
		/*下载到本地文件*/
		String localFile=localPath+"\\"+filename;
		Long tempfilename=Calendar.getInstance().getTimeInMillis();
		/*解密后文件*/
		String decryptFile=localPath+"\\"+tempfilename+postfix;
		/*解密后服务地址*/
		String onlink_path=prop.get("pdf.temp.path")+"\\"+tempfilename+postfix;
		String url=prop.get("upload.pdf.url");
		int port=Integer.parseInt(prop.get("upload.pdf.port"));
		String username=prop.get("upload.pdf.username");
		String password=prop.get("upload.pdf.password");
		reMap.put("suc", true);
		try {
			//下载pdf文件
			/*boolean flag = Ftp.downFile(url, port, username,
					password, "/"+ftpdir, filename, localPath);
				   System.out.println(flag);*/
			//FTPUtil.downFile(url, port, username, password, ftpdir, filename, localPath, postfix);
			//解密
			new FileEncodeAndDecode(prop.get("encrypt.key")).decrypt(encryptpath, decryptFile);
			
			/*response.setContentType("image/jpeg;charset=GBK");
			
            OutputStream os = response.getOutputStream();
            
            InputStream in =new ByteArrayInputStream(toByteArray(decryptFile));
            int len;
            byte[] buf = new byte[1024];
            while ((len = in.read(buf, 0, 1024)) != -1) {
                os.write(buf, 0, len);
            }
            os.close();*/
		}  catch (IOException e) {
			reMap.put("suc", false);
			e.printStackTrace();
		} catch (Exception e) {
			reMap.put("suc", false);
			e.printStackTrace();
		}
		//删除文件
		//FileUtil.deleteFile(localFile);
		//FileUtil.deleteFile(decryptFile);
		reMap.put("url", onlink_path);
		
		return reMap;
	}
    
    @RequestMapping(value = "printPDF")
    @ResponseBody
    public Map<String,Object> printPDF(HttpServletRequest request){
    	Map<String,Object> reMap=new HashMap<String,Object>();
    	reMap.put("result", true);
    	/*取资源文档目录*/
		String path = Thread.currentThread().getContextClassLoader().getResource("").getPath();
		/*读取配置文件*/
		Map<String,String> prop=SetSystemProperty.propertiesToMap(path+"/config.properties");
		/*取项目根目录*/
		String strDirPath = request.getSession().getServletContext().getRealPath("/");
		/*打印临时目录*/
		String printPath=strDirPath+prop.get("print.temp")+Calendar.getInstance().getTimeInMillis();
		/*创建多级本地目录*/
		FileUtil.createMultilayerFile(printPath);
		String pdfurl=prop.get("print.temp")+Calendar.getInstance().getTimeInMillis()+".pdf";
    	String newFile=strDirPath+pdfurl;
    	
    	int sum=0;
    	List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
		try {
			String paths = URLDecoder.decode(request.getParameter("paths"), "UTF-8");
			String [] pathArr=paths.split(",");
	    	for (int i = 0; i < pathArr.length; i++) {
	    		Map<String,Object> map=new HashMap<String,Object>();
				String decryptFile=printPath+"\\"+Calendar.getInstance().getTimeInMillis()+".pdf";
				//解密
				try {
					map.put("filename", pathArr[i].substring(pathArr[i].lastIndexOf("/")+1));
					new FileEncodeAndDecode(prop.get("encrypt.key")).decrypt(pathArr[i], decryptFile);
					map.put("msg", "<font color=\"green\">有</font>");
					sum++;
				} catch (Exception e) {
					map.put("msg", "<font color=\"red\">无</font>");
				}
				list.add(map);
			}
	    	
	    	//把需要打印的pdf文件合成一个pdf
	    	PrintUtils.compose(printPath, newFile);
	    	//打印合成的pdf文件
	    	//PrintUtils.printWithDialog(newFile);
	    	
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			reMap.put("result", false);
			reMap.put("msg", e.getMessage());
			System.out.println(e.getMessage());
		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} 
		//删除解密后的临时文件夹
    	FileUtil.deleteDirectory(printPath);
    	reMap.put("list", list);
    	reMap.put("pdfurl", pdfurl);
    	reMap.put("sum", sum);
    	//删除合成文件
    	//FileUtil.deleteFile(newFile);
    	return reMap;
    }
    
    private static byte[] toByteArray(String filePath) throws IOException {
    	InputStream in = new FileInputStream(filePath);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024 * 4];
        int n = 0;
        while ((n = in.read(buffer)) != -1) {
            out.write(buffer, 0, n);
        }
        return out.toByteArray();
    }
    
    /**
     * 病案浏览页面单个图片分类模板申请
     */
    @RequestMapping("confirmSApplyImg")
    @ResponseBody
    public Object confirmSApplyImg(HttpServletRequest request){
        Tsysuser userObject = (Tsysuser) request.getSession().getAttribute(GlobalStatic.USER_SESSION_OBJECT);
        
        String fzyid = request.getParameter("fzyid");  //住院id
        String imgid = request.getParameter("imgid");  //图片分类id
        String imgname = request.getParameter("imgname");  //图片分类名称
        String sApplyPurpose = request.getParameter("sApplyImgPurpose");  //申请目的
        String sBrowseDays = request.getParameter("sBrowseImgDays");  //申请浏览天数
        String sApplyRemark = request.getParameter("sApplyImgRemark");  //申请描述
        
        Map<String, Object> map = new HashMap<String, Object>();
        
        map.put("fzyid", fzyid);
        map.put("imgid", imgid);
        map.put("imgname", imgname);
        map.put("sApplyPurpose", sApplyPurpose);
        map.put("sBrowseDays", sBrowseDays);
        map.put("sApplyRemark", sApplyRemark);
        map.put("user", userObject.getFcode());
        map.put("fjysqr", userObject.getFname());
        
        return iMedicalCheckService.confirmSApplyImg(map);
    }
    
    /*********************************************************************
     ***************************病案高级查询*******************************
     *********************************************************************/
    
    /**
     * 病案高级查询-主页面跳转
     * @author [lv tang wei]
     * @return
     * [2017年6月5日]
     */
    @RequestMapping("/MedicalAdvancedInquiry")
    public String toMedicalAdvancedInquiry(){
        return "MedicalCheckManage/MedicalAdvancedInquiry";
    }
    
    /**
     * 病案高级查询-可选条件树查询
     * @author [lv tang wei]
     * Describe:
     * @param text 字段条件
     * @return
     * [2017年6月5日]
     */
    @ResponseBody
    @RequestMapping("/getQuerySelfCondition")
    public List<Map<String,Object>> getQuerySelfCondition(){
    	try {
			return iMedicalCheckService.getQuerySelfCondition();
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return null;
    }
    
    /**
     * 病案高级查询-新增个人模板
     * @author [lv tang wei]
     * Describe:
     * @param request
     * @return
     * [2017年6月6日]
     */
    @ResponseBody
    @RequestMapping("/addTemplate")
    public Object addTemplate(HttpServletRequest request){
    	String fmbmc = request.getParameter("fmbmc");  //模板名称
    	String ftype = request.getParameter("ftype");  //模板类型
    	int type=Integer.parseInt(ftype==null?"1":ftype);
    	Tsysuser userObject = (Tsysuser) request.getSession().getAttribute(GlobalStatic.USER_SESSION_OBJECT);
    	try {
			iMedicalCheckService.addTemplate(fmbmc, userObject.getFcode(), type);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		};
		return true;
    }
    
    /**
     * 病案高级查询-模板条件组--根据模板id获取条件组
     * @author [lv tang wei]
     * Describe:
     * @param request
     * @return
     * [2017年6月6日]
     */
    @ResponseBody
    @RequestMapping("/queryConditionGroup")
    public Map<String,Object> queryConditionGroup(HttpServletRequest request){
    	Map<String,Object> reMap=new HashMap<String,Object>();
    	String mbid = request.getParameter("mbid");  //模板id
    	reMap.put("rows", this.iMedicalCheckService.queryConditionGroup(mbid));
    	return reMap;
    }
    
    /**
     * 病案高级查询-模板条件组--新增
     * @author [lv tang wei]
     * Describe:
     * @param request
     * @return
     * [2017年6月7日]
     */
    @ResponseBody
    @RequestMapping("/addConditionGroup")
    public Object addConditionGroup(HttpServletRequest request){
    	String mbid = request.getParameter("mbid");  //模板id
    	String tjzmc = request.getParameter("tjzmc");  //条件组名称
    	String pid = request.getParameter("pid");  //父节点id
    	String px = request.getParameter("px");  //排序
    	try {
			iMedicalCheckService.addConditionGroup(mbid, pid, tjzmc, px);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		};
		return true;
    }
    
    /**
     * 病案高级查询-模板条件组--修改
     * @author [lv tang wei]
     * Describe:
     * @param request
     * @return
     * [2017年6月7日]
     */
    @ResponseBody
    @RequestMapping("/updateConditionGroup")
    public Object updateConditionGroup(HttpServletRequest request){
    	String id = request.getParameter("id");  //id
    	String tjzmc = request.getParameter("tjzmc");  //条件组名称
    	String px = request.getParameter("px");  //排序
    	String pid = request.getParameter("pid");  //父级id
    	String gx = request.getParameter("gx");  //与上一排序的关系
    	try {
			iMedicalCheckService.updateConditionGroup(id, tjzmc, px,pid,gx);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		};
		return true;
    }
    
    /**
     * 病案高级查询-模板条件组--删除
     * @author [lv tang wei]
     * Describe:
     * @param request
     * @return
     * [2017年6月7日]
     */
    @ResponseBody
    @RequestMapping("/deleteConditionGroup")
    public Object deleteConditionGroup(HttpServletRequest request){
    	String id = request.getParameter("id");  //id
    	try {
			iMedicalCheckService.deleteConditionGroup(id);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		};
		return true;
    }
    
    /**
     * 病案高级查询-条件明细--取条件组下明细
     * @author [lv tang wei]
     * Describe:
     * @param request
     * @return
     * [2017年6月12日]
     */
    @ResponseBody
    @RequestMapping("/queryCondition")
    public Map<String,Object> queryCondition(HttpServletRequest request){
    	Map<String,Object> reMap=new HashMap<String,Object>();
    	String zid = request.getParameter("zid");  //模板id
    	reMap.put("rows", this.iMedicalCheckService.queryCondition(zid));
    	return reMap;
    }
    
    /**
     * 病案高级查询-条件明细--取条件组下某个条件明细
     * @author [lv tang wei]
     * Describe:
     * @param request
     * @return
     * [2017年6月12日]
     */
    @ResponseBody
    @RequestMapping("/queryConditionByCode")
    public Object queryConditionByCode(HttpServletRequest request){
    	String zid = request.getParameter("zid");  //模板id
    	String code = request.getParameter("code");  //模板code
    	return this.iMedicalCheckService.getConditionByCode(zid,code);
    }
    
    /**
     * 病案高级查询-条件明细--新增
     * @author [lv tang wei]
     * Describe:
     * @param request
     * @return
     * [2017年6月12日]
     */
    @ResponseBody
    @RequestMapping("/addCondition")
    public Object addCondition(SzhCxmbtjmx mx,HttpServletRequest request){
    	try {
			iMedicalCheckService.addCondition(mx);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		};
		return true;
    }
    
    /**
     * 病案高级查询-条件明细--修改
     * @author [lv tang wei]
     * Describe:
     * @param request
     * @return
     * [2017年6月7日]
     */
    @ResponseBody
    @RequestMapping("/updateCondition")
    public Object updateCondition(SzhCxmbtjmx mx,HttpServletRequest request){
    	try {
			iMedicalCheckService.updateCondition(mx);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		};
		return true;
    }
    
    /**
     * 病案高级查询-条件明细--删除
     * @author [lv tang wei]
     * Describe:
     * @param request
     * @return
     * [2017年6月7日]
     */
    @ResponseBody
    @RequestMapping("/deleteCondition")
    public Object deleteCondition(HttpServletRequest request){
    	String id = request.getParameter("fid");  //id
    	try {
			iMedicalCheckService.deleteCondition(id);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		};
		return true;
    }
    
    /**
     * 病案高级查询-SQL测试
     * @author [lv tang wei]
     * Describe:
     * @param request
     * @return
     * [2017年6月7日]
     */
    @ResponseBody
    @RequestMapping("/testSql")
    public Map<String,Object> testSql(String mbid){
    	Map<String,Object> reMap=new HashMap<String, Object>();
    	try {
    		Map<String,Object> temp=iMedicalCheckService.getTemplateByID(mbid);
			reMap.put("suc", true);
			reMap.put("sql", temp.get("FQL"));
		} catch (Exception e) {
			e.printStackTrace();
			reMap.put("suc", false);
			reMap.put("msg", e.getMessage());
		}
    	return reMap;
    }
    
    @ResponseBody
    @RequestMapping("/getTemplateSQLZH")
    public Map<String,Object> getTemplateSQLZH(String mbid){
    	Map<String,Object> reMap=new HashMap<String, Object>();
    	try {
    		Map<String,Object> temp=iMedicalCheckService.getTemplateByID(mbid);
			reMap.put("suc", true);
			reMap.put("sqlzh", temp.get("FSQLZH"));
			reMap.put("sql", temp.get("SQL"));
			reMap.put("wsql", temp.get("FSQL"));
		} catch (Exception e) {
			e.printStackTrace();
			reMap.put("suc", false);
			reMap.put("msg", e.getMessage());
		}
    	return reMap;
    }
    
    @ResponseBody
    @RequestMapping("/medicalAdvancedInquiryBatchBrowseApplyQuery")
    public Map<String,Object> medicalAdvancedInquiryBatchBrowseApplyQuery(String mbid,HttpServletRequest request){
    	Map<String,Object> reMap=new HashMap<String, Object>();
    	Tsysuser userObject = (Tsysuser) request.getSession().getAttribute(GlobalStatic.USER_SESSION_OBJECT);
        Map<String, Object> map = getParameterMap(request);
        map.put("fcode", userObject.getFcode());
    	try {
    		reMap=iMedicalCheckService.medicalAdvancedInquiryBatchBrowseApplyQuery(map);
    		reMap.put("rows", formatListDate(reMap.get("rows")));
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return reMap;
    } 
    
    /**
     * 根据字段模板id加载过滤字段信息
     */
    @RequestMapping("loadFieldsByTempFilterId")
    @ResponseBody
    public Object loadFieldsByTempFilterId(HttpServletRequest request){
        String mbID = request.getParameter("mbID");  //模板id
        return iMedicalCheckService.loadFieldsByTempFilterId(mbID);
    }
    
    //病案错误报告处理  查询
	@RequestMapping("/queryAllErrossb")
    @ResponseBody 
    public Object queryAllErrossb(HttpServletRequest request){
		String rqlx = request.getParameter("rqlx");
		String date1 = request.getParameter("date1");
		String date2 = request.getParameter("date2");
		String cwlx = request.getParameter("cwlx");
		String sfcl = request.getParameter("sfcl"); 
		
		String page = request.getParameter("page");
    	String rows = request.getParameter("rows");
    	
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("rqlx", rqlx);
		map.put("date1", date1);
		map.put("date2", date2);
		map.put("cwlx", cwlx);
		map.put("sfcl",sfcl ); 
		
		map.put("page", page);
     	map.put("rows", rows);
     	PageHelper resultPage = iMedicalCheckService.queryAllErrossb(map);
     	return resultPage;
	}
  	
	
	//病案错误报告处理   处理状态修改
	@RequestMapping("submitFstate")
    @ResponseBody 
    public Object submitFstate(HttpServletRequest request){ 
		 Tsysuser userObject = (Tsysuser) request.getSession().getAttribute(GlobalStatic.USER_SESSION_OBJECT);
	        
        String FID = request.getParameter("FID");        //id  
        String FSTATE = request.getParameter("FSTATE"); //处理状态
        String FCLYJ = request.getParameter("FCLYJ");  //处理意见 
        
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("FID", FID);
        map.put("FSTATE", FSTATE);
        map.put("FCLYJ", FCLYJ);
        map.put("user", userObject);
        
        return iMedicalCheckService.submitFstate(map);
    }  
	
	 //人员浏览统计 查询
	@RequestMapping("/SumMedicalStatistical")
    @ResponseBody 
    public Object SumMedicalStatistical(HttpServletRequest request){ 
		String date1 = request.getParameter("date1");
		String date2 = request.getParameter("date2");
		String FUSERCODE = request.getParameter("FUSERCODE");  
		String FUSERNAME = request.getParameter("FUSERNAME");  
		
		String page = request.getParameter("page");
    	String rows = request.getParameter("rows");
    	
		Map<String, Object> map = new HashMap<String, Object>(); 
		map.put("date1", date1);
		map.put("date2", date2);
		map.put("FUSERCODE", FUSERCODE); 
		map.put("FUSERNAME", FUSERNAME); 
		
		map.put("page", page);
     	map.put("rows", rows);
     	PageHelper helper=null;
		try {
			helper = iMedicalCheckService.SumMedicalStatistical(map);
		} catch (Exception e) {
			e.printStackTrace();
		} 
      
     	return helper;
	}
	
	//人员浏览统计 详情
	@RequestMapping("/MbrowseInfo")
    @ResponseBody 
    public Object MbrowseInfo(HttpServletRequest request){  
		String date1 = request.getParameter("date1");
		String date2 = request.getParameter("date2");
		String FUSERNAME = request.getParameter("FUSERNAME");     
		
		String page = request.getParameter("page");
    	String rows = request.getParameter("rows");
    	
		Map<String, Object> map = new HashMap<String, Object>(); 
		map.put("date1", date1);
		map.put("date2", date2);
		map.put("FUSERNAME", FUSERNAME);  
		
		map.put("page", page);
     	map.put("rows", rows);
     	PageHelper helper=null;
		try {
			helper = iMedicalCheckService.MbrowseInfo(map);
		} catch (Exception e) {
			e.printStackTrace();
		} 
      
     	return helper;
	} 
 
}
